//
//  RegisterVC.swift
//  ShareUmbrella
//
//  Created by keng fu on 2017/8/9.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import Foundation
import UIKit
import YSKit
import TSMessages

class RegisterVC: YSBaseViewController, UITextFieldDelegate {
    var time: Int = 0
    var timer: Timer!
    var isRead: Bool = false
    
    var strPwd: String = ""
    var isShowPwd: Bool = false
    var strAgPwd: String = ""
    var isShowAgPwd: Bool = false
    
    @IBOutlet weak var tf_name: UITextField!
    
    @IBOutlet weak var tf_code: UITextField!

    @IBOutlet weak var tf_pwd: UITextField!
    
    @IBOutlet weak var tf_pwdAg: UITextField!
    
    @IBOutlet weak var btn_verify: UIButton!
    
    @IBOutlet weak var btn_read: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.btn_read.ys.setImageAndTitle(imageName: "icon_unread", title: "我已经阅读并同意", type: .left, space: 5.0)
        self.tf_pwd.delegate = self;
        self.tf_pwdAg.delegate = self;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true;
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false;
    }

    @IBAction func backAction(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    @IBAction func sendVerifyCode(_ sender: UIButton) {
        if !(tf_name.text?.isPhone("CN"))! {
            TSMessage.showNotification(withTitle: I18n("VC.login.notphone"), type: .warning)
            return
        }
        
        HUD.show()
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.getCode(phone: self.tf_name.text!))).subscribe(onNext: { [weak self] (data) in
            //
            HUD.hide()
            guard let `self` = self else {
                return
            }
            Auth.token = (data?["token"].stringValue)!
            sender.isEnabled = false
            self.time = 60
            self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (Timer) in
                self.btn_verify.setTitle(String.init(format: "%lds", self.time), for: UIControlState.normal)
                if self.time == 0 {
                    self.time = 60
                    self.btn_verify .setTitle(I18n("VC.login.verifybtn.title"), for: UIControlState.normal)
                    self.btn_verify.isEnabled = true
                    self.timer.invalidate()
                }else{
                    self.time -= 1
                }
            })

            }, onError: { [weak self](ErrorType) in
                HUD.hide()
                guard let  `self` = self else {
                    return
                }
                self.handle(withError: ErrorType)
        })

    }
    
    @IBAction func registerAction(_ sender: UIButton) {
        if self.verifyInput() {
            HUD.show()
            _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.registe(phone: self.tf_name.text!, code: self.tf_code.text!, password: self.tf_pwd.text!, token: Auth.token))).subscribe(onNext: { [weak self] (data) in
                //
                HUD.hide()
                guard let _ = self else {
                    return
                }
                Auth.login((data?["token"].string)!)
                }, onError: { [weak self](ErrorType) in
                    HUD.hide()
                    guard let  `self` = self else {
                        return
                    }
                    self.handle(withError: ErrorType)
            })
        }

    }
    
    func verifyInput() -> Bool {
        if tf_name.text?.characters.count == 0 {
            TSMessage.showNotification(withTitle: I18n("VC.login.noname"), type: .warning)
            return false;
        }
        
        if tf_pwd.text?.characters.count == 0, tf_pwdAg.text?.characters.count == 0{
            TSMessage.showNotification(withTitle: I18n("VC.login.nopwd"), type: .warning)
            return false;
        }
        
        if (tf_pwd.text?.characters.count)! < 6, (tf_pwdAg.text?.characters.count)! < 6 {
            TSMessage.showNotification(withTitle: I18n("VC.login.pwdlength"), type: .warning)
            return false;
        }
        
        if (tf_pwd.text?.characters.count)! > 20, (tf_pwdAg.text?.characters.count)! > 20 {
            TSMessage.showNotification(withTitle: I18n("VC.login.pwdlengthtoolong"), type: .warning)
            return false;
        }
        
        if !(tf_name.text?.isPhone("CN"))! {
            TSMessage.showNotification(withTitle: I18n("VC.login.notphone"), type: .warning)
            return false;
        }
        
        if (tf_code.text?.characters.count == 0) {
            TSMessage.showNotification(withTitle: I18n("VC.login.nocode"), type: .warning)
            return false;
        }
        
        if (tf_pwdAg.text != tf_pwd.text) {
            TSMessage.showNotification(withTitle: I18n("VC.login.pwdnotsame"), type: .warning)
            return false;
        }
        
        if !isRead {
            TSMessage.showNotification(withTitle: I18n("VC.login.agreeprotocal"), type: .warning)
            return false;
        }
        
        return true;
    }
    
    
    @IBAction func readAction(_ sender: UIButton) {
        isRead = !isRead;
        btn_read .setImage(UIImage(named:isRead ? "icon_read" : "icon_unread"), for: .normal)
    }
    
    @IBAction func agreeAction(_ sender: UIButton) {
        self.ys.push(AgreementVC())
    }
    
    @IBAction func pwdShowAction(_ sender: Any) {
        self.strPwd = self.tf_pwd.text!;
        isShowPwd = !isShowPwd;
        if (isShowPwd) {
            self.tf_pwd.isSecureTextEntry = false
            self.tf_pwd.text = self.strPwd;
        }else{
            self.tf_pwd.isSecureTextEntry = true
            self.tf_pwd.text = self.strPwd;
        }
        self.tf_pwd.keyboardType = .asciiCapable;
    }
    
    @IBAction func agpwdShowAction(_ sender: Any) {
        self.strAgPwd = self.tf_pwdAg.text!;
        isShowAgPwd = !isShowAgPwd;
        if (isShowAgPwd) {
            self.tf_pwdAg.isSecureTextEntry = false
            self.tf_pwdAg.text = self.strAgPwd;
        }else{
            self.tf_pwdAg.isSecureTextEntry = true
            self.tf_pwdAg.text = self.strAgPwd;
        }
        self.tf_pwdAg.keyboardType = .asciiCapable;
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    // MARK: - textfield delegate
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        _ = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        let existedLength = textField.text?.characters.count
        let selectedLength = range.length
        let replaceLength = string.characters.count
        _ = existedLength! - selectedLength + replaceLength
        if textField.isEqual(self.tf_pwd), deptNameInputShouldChinese(string) {
            return false;
        }
    
        return true;
    }
    
    func deptNameInputShouldChinese(_ input: String) -> Bool {
        let regex = "[\\u4e00-\\u9fa5]+"
        let hanziPre = NSPredicate(format: "SELF MATCHES %@", regex)

        if hanziPre .evaluate(with: input) {
            TSMessage.showNotification(withTitle: I18n("VC.login.noChineseCharecter"), type: .warning)
            return true
        }
        
        return false
    }

}


